import React, { useState } from 'react';
import { Upload, Button, message, Modal } from 'antd';
import FileDownload from '../components/FileDownload';
import { fileContent } from './constant';
import store from '../../../../store';
import { JSONObject } from '../../../schema/common';
import './index.scss';

interface Props {
  onPhoneFromChild: (data: string[]) => void;
}

const FileScanner: React.FC<Props> = ({ onPhoneFromChild }) => {
  const [uploadLoading, setUploadLoading] = useState(false);
  const beforeUpload = file => {
    const allowedExtensions = ['.xls', '.xlsx', '.csv', '.et'];
    const fileName = file.name.toLowerCase();
    const isValid = allowedExtensions.some(ext => fileName.endsWith(ext));

    if (!isValid) {
      message.error('仅支持上传 xls、xlsx、csv 或 et 格式的文件');
      return Upload.LIST_IGNORE;
    }
  };

  const handleUpload: any = ({ file, onSuccess, onError }) => {
    const formData = new FormData();
    formData.append('file', file);

    setUploadLoading(true);
    const encryptToken = (store.getState() as JSONObject).encryptToken;
    // process.env.REACT_APP_API_URL +
    fetch('/weathersms/web/industry/smshangmain/analyzeFile', {
      method: 'POST',
      body: formData,
      headers: { encryptToken },
    })
      .then(response => response.json())
      .then(({ code, msg, data }) => {
        if (code === 0) {
          // 发给父级
          onPhoneFromChild(data.phone_list);
          message.success('文件上传解析成功');
          onSuccess('ok');
        } else {
          Modal.error({
            title: '文件上传失败',
            content: msg,
            closable: true,
            className: 'error-popup', // 这个css为了改变antd内部自己的元素
          });
          onError('文件上传失败');
        }
      })
      .catch(error => {
        message.error('文件上传失败');
        onError('文件上传失败');
      })
      .finally(() => {
        setUploadLoading(false);
      });
  };

  return (
    <div className="file-scanner">
      <Upload
        customRequest={handleUpload}
        beforeUpload={beforeUpload}
        fileList={[]}
        accept=".xls,.xlsx,.csv,.et"
      >
        <Button loading={uploadLoading}>文件上传</Button>
      </Upload>
      <span>请上传小于15M的xls、xlsx、csv或et文件</span>
      <FileDownload fileContent={fileContent} />
    </div>
  );
};

export default FileScanner;
